﻿using System;
using System.Data.Entity;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using VietTrips.Domain.Contexts;
using VietTrips.Domain.Interfaces;
using VietTrips.Domain.Models;

namespace VietTrips.Domain.Repositories
{
    public class UserRepository : IUserRepository
    {
        private readonly UsersContext _context = new UsersContext();

        public IQueryable<UserProfile> All
        {
            get { return _context.UserProfiles; }
        }
        public IQueryable<UserProfile> AllIncluding(params Expression<Func<UserProfile, object>>[] includeExpressions)
        {
            throw new NotImplementedException();
        }

        public UserProfile Find(int id)
        {
            return _context.UserProfiles.Find(id);
        }

        public void Insert(UserProfile entity)
        {
            // Không cho phép insert
            throw new NotImplementedException();
        }

        public void Update(UserProfile userProfile)
        {
            _context.Entry(userProfile).State = EntityState.Modified;
        }

        public void Delete(int id)
        {
            var user = Find(id);
            user.IsDeleted = true;
            user.LastModified = DateTime.UtcNow;
            Update(user);
        }

        public void Save()
        {
            _context.SaveChanges();
        }

        public void Dispose()
        {
            _context.Dispose();
        }

        public UserProfile FindByUsername(String userName)
        {
            var query = _context.UserProfiles.Where(a => a.UserName == userName).Take(1).ToList();
            return query.Count > 0 ? query.ElementAt(0) : null;
        }

        public Role FindRole(String roleName)
        {
            var query = _context.Roles.Where(r => r.RoleName.ToLower().Equals(roleName.ToLower())).Take(1).ToList();
            return query.Count > 0 ? query.ElementAt(0) : null;
        }
    }
}
